package com.fclassroom.controller.interceptor;

import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fclassroom.ErrorCode;
import com.jason.framework.util.StringUtil;

public class ControlHandlerInterceptor extends HandlerInterceptorAdapter {
	private final Logger loger = LoggerFactory.getLogger(this.getClass());
	private static final String ENCODING_DEFAULT = "UTF-8";
	private static final String ContentType_json = "application/json;charset=" + ENCODING_DEFAULT;
	private static final String ContentType_html = "text/html;charset=" + ENCODING_DEFAULT;

	@Autowired
	private MessageSource messageSource;

	
	/**
	 * 支持跨域的域名
	 */
	private List<String> accessAllowedFrom;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String local = request.getParameter("locale");
		String code = ErrorCode.ACCESS_TOKEN_null;
		if ("zh".equals(local))
			LocaleContextHolder.setLocale(Locale.CHINESE, true);
		else if ("en".equals(local))
			LocaleContextHolder.setLocale(Locale.ENGLISH, true);
		else {
			LocaleContextHolder.setLocale(request.getLocale(), true);
		}
		request.setAttribute("site_title", messageSource.getMessage("site_title", null, "", LocaleContextHolder.getLocale()));
		response.setContentType(ContentType_json);
		response.setCharacterEncoding(ENCODING_DEFAULT);
		request.setCharacterEncoding(ENCODING_DEFAULT);

		if("options".equals(request.getMethod().toLowerCase())){//说明是跨域请求
			doCORS(response, request);
		}
		
		return true;
	}
	/**
	 * 执行跨域请求的封装。
	 * @author Jason
	 * @date 2016年6月14日 下午11:25:58
	 * @param res
	 * @param req
	 */
	private void doCORS(HttpServletResponse res,HttpServletRequest req){
		
		res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		res.setHeader("Access-Control-Max-Age", "3600");
		res.setHeader("Access-Control-Allow-Credentials", "true");
		
		res.addHeader("Access-Control-Allow-Headers", req.getHeader("Access-Control-Request-Headers")); 
		String referer = req.getHeader("Origin");
		if(StringUtil.isEmpty(referer)){
			referer = req.getHeader("Referer");
		}
		if(StringUtil.isNotEmpty(referer)){
			for (String str : accessAllowedFrom) {
				Matcher matcher = Pattern.compile(str).matcher(referer);
				if(matcher.find()){
			        String host=matcher.group();
			        res.setHeader("Access-Control-Allow-Origin", host);
					break;
			    }
			}
		    
		}
	}
	public List<String> getAccessAllowedFrom() {
		return accessAllowedFrom;
	}

	public void setAccessAllowedFrom(List<String> accessAllowedFrom) {
		this.accessAllowedFrom = accessAllowedFrom;
	}


}
